<?php
	
	namespace App\Http\Controllers\Admin\ExportContract;
	
	use Illuminate\Http\Request;
	use App\Http\Controllers\Controller;
	use DB;
	use PhpOffice\PhpSpreadsheet\Cell\DataType;
	use PhpOffice\PhpSpreadsheet\IOFactory;
	use QrCode;
//	分发单
	class ExportContractFFHuiBangJianCeController extends Controller
	{
		
		private function getvolclass($val)
		{
			if ($val->class === '/') {
				# 电压等级
				$voltage_class = "{$val->voltage}";
			}
			else if ($val->voltage === '/') {
				# 分类
				$voltage_class = "{$val->class}";
			}
			else {
				# 电压等级+分类
				$voltage_class = "{$val->voltage}/{$val->class}";
			}
			return $voltage_class;
		}
		
		public function export(Request $request)
		{
			// sleep (5);
			$contract_id = $request->id;
			$data_gaiyao1 = DB::table('a_contract_gaiyao')->where('contract_id', $contract_id)->orderBy('id', 'asc')->get();
			if ($data_gaiyao1->isEmpty()) {
				return '内容为空';
			}
			$data_contract = DB::table('a_contract')->find($contract_id);
			// dd($data_contract);
			
			// dd(base_path());
			// dd(public_path());
			$app_name = config('constant.app_name');
			$template_file = "./storage/ExcelTemplate/检验分发单{$app_name}.xls"; //考虑到兼容Linux，斜杠用“/”
			if (!file_exists($template_file)) {
				return '模板文件不存在';
			}
			$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file); //读取模板文件
			$worksheet = $spreadsheet->getSheet(0); //按索引获取表单，从 0 开始
			$setting = DB::table('setting')->find(1);
            $worksheet->getCell('A1')->setValue($setting->name_rep);  //报告名称
            $worksheet->getCell('C4')->setValue($data_contract->batchNum); //合同编号
            $worksheet->getCell('H4')->setValue($data_contract->test_kind); //检测性质
            $worksheet->getCell('C5')->setValue($data_contract->deadline); //要求完成日期
            $worksheet->getCell('H5')->setValue($data_contract->creator); //样品接收人
            // $worksheet->getCell('C6')->setValue($data_contract->creator); //认可标志
			$data_gaiyao = [];
			$rowIndex = $initRowIndex = 7;
			$totalCount  = 0;
			foreach ($data_gaiyao1 as $item) {
				$key = "{$item->tool_id}-{$item->vol_id}-{$item->class_id}-{$item->item_names}-{$item->std_num}";
				if(isset($data_gaiyao[$key])){
					$data_gaiyao[$key]->count += $item->count;
					$data_gaiyao[$key]->bar_codes .= '、'.$item->bar_codes;
				}else{
					$data_gaiyao[$key] = $item;
				}
			}
			foreach ($data_gaiyao as $val) {
				if ($totalCount > 0) {
					$worksheet->insertNewRowBefore($rowIndex, 1); //在第$rowIndex行之前插入1个新行
					// $worksheet->getRowDimension('10')->setRowHeight(15);//设置行高
					// $worksheet->mergeCells('A18:E22');//合并单元格
					$worksheet->mergeCells('A' . $rowIndex . ':B' . $rowIndex);
					$worksheet->mergeCells('C' . $rowIndex . ':C' . $rowIndex);
					$worksheet->mergeCells('D' . $rowIndex . ':D' . $rowIndex);
					$worksheet->mergeCells('E' . $rowIndex . ':F' . $rowIndex);
					$worksheet->mergeCells('G' . $rowIndex . ':H' . $rowIndex);
					$worksheet->mergeCells('I' . $rowIndex . ':I' . $rowIndex);
				}

				$worksheet->setCellValue('A'.$rowIndex, $val->tool_name);          //样品名称
				$volClass = $this->getvolclass($val);
				$worksheet->setCellValue('C'.$rowIndex, $volClass); //电压等级/分类
				$worksheet->setCellValue('D'.$rowIndex, $val->count . $val->unit); //数量
				$worksheet->setCellValue('E'.$rowIndex, $val->bar_codes);          //编号
				$worksheet->setCellValue('G'.$rowIndex, $val->item_names); //检验项目
				$worksheet->setCellValue('I'.$rowIndex, $val->std_num); //检测依据
				//设置行高依据：  电压等级/分类  检验项目 
				$volClassLen = (strlen($volClass)+mb_strlen($volClass,"UTF8"))/2; //文字按两个字符算，英文和数字按一个字符算
				$volBei = ceil($volClassLen/10);
				$itemBei = ceil(mb_strlen($val->item_names)/15);
				$bei = $volBei > $itemBei ? $volBei : $itemBei;
				// dump($val->item_names,mb_strlen($val->item_names));
				if ($bei > 1) {
					$height = $bei * 16;
					$worksheet->getRowDimension($rowIndex)->setRowHeight($height);
				}else{
					$worksheet->getRowDimension($rowIndex)->setRowHeight(20);
				}
				// break;
				$rowIndex++;
				$totalCount += $val->count;
			}
			// dd(111);
			$sumRows = $rowIndex - $initRowIndex; //计算共有多少行数据，每行数据在结论页占10个高位置
			$toheight = 45; //初始化行高
			$height = 10 * $sumRows;
			if($height > $toheight){
				$toheight = $height;
			}
			$worksheet->getRowDimension($rowIndex)->setRowHeight($toheight);
			$worksheet->getCell('C' . ($rowIndex + 1))->setValue('共计：' . $totalCount . '件；其他备注：' . $data_contract->remark); //备注

			//----------直接在浏览器下载----start
			$file_name = "检验分发单" . $data_contract->batchNum . ".xls";                                                        //输出的文件名称
			// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
			header('Content-Type: application/vnd.ms-excel');                                                               //告诉浏览器输出Excel 03版本文件
			header('Content-Disposition: attachment;filename=' . urlencode($file_name));                                    //告诉浏览器输出的文件名称
			header('Cache-Control: max-age=0');                                                                             //禁止缓存
			//----------直接在浏览器下载----end
			
			
			$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
			$writer->setPreCalculateFormulas(false); //禁用公式预先计算
			// $writer->save('write.xls');//将Excel文件保存在服务器的磁盘上
			$writer->save('php://output');           //直接在浏览器下载
			
			/* //未测试通过
			// $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
			$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf');
			$writer->setPreCalculateFormulas(false);//禁用公式预先计算
			$writer->save("05featuredemo.pdf"); */
			
			//为了防止内存泄露，建议用完手动清理
			$spreadsheet->disconnectWorksheets();
			unset($spreadsheet);
		}
	}
